package api

import (
	"net/http"

	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"

	"hytx_media/pkg/app"
	"hytx_media/pkg/e"
	"hytx_media/pkg/util"
	"hytx_media/service/auth_service"
	"hytx_media/service/media_user_login_log_service"
	"golang.org/x/crypto/bcrypt"
)

type auth struct {
	Username string `valid:"Required; MaxSize(50)"`
	Password string `valid:"Required; MaxSize(58)"`
}

// @Summary 登录授权
// @Produce  json
// @Param username param string true "username"
// @Param password param string true "password"
// @Success 200 {string} json "
// 		{
// 		   "code": 200,
// 		   "data": {
// 		       "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjY4Nzk3NDc4ZTZiYmI0ZTU4YWEwZTVhZjg2NmJjMDEwMzQ4ODRmZTJjZWRmNjhiMzlmNjQ5NjIzNmIiLCJwYXNzd29yZCI6IjY4Nzk3NDc4ZTZiYmI0ZTU4YWEwZTVhZjg2MGI1NzExMWQyYTMwMTM1YTEwZTJjNmRjYzY5YThjNWIiLCJleHAiOjE1Mjk5OTMyODEsImlzcyI6Imdpbi1ibG9nIn0.g5Sf_gOaV3Yx5xbfgXrJ8gvBEbVUA-ki9KvqOdtbJlc"
// 		   },
// 		   "msg": "ok"
//		}"
func GetAuth(c *gin.Context) {
	appG := app.Gin{C: c}
	valid := validation.Validation{}

	username := c.PostForm("username")
	password := c.PostForm("password")

	a := auth{Username: username, Password: password}
	ok, _ := valid.Valid(&a)

	if !ok {
		app.MarkErrors(valid.Errors)
		appG.Response(http.StatusOK, e.INVALID_PARAMS, false)
		return
	}

	authService := auth_service.Auth{Username: username}

	mediaUser, err := authService.Check()

	if mediaUser == nil || err != nil {
		appG.ResponseMsg(http.StatusOK, "账号错误", false)
		return
	}

	if mediaUser.IsEnabled == 1 && mediaUser.Status == 3 {
		appG.ResponseMsg(http.StatusOK, "已被封停", false)
		return
	}

	if mediaUser == nil {
		appG.ResponseMsg(http.StatusOK, "电话错误", false)
		return
	}

	// 验证密码是否正确
	//_, err = password_hash.Verify(mediaUser.Password, password)
	err = bcrypt.CompareHashAndPassword([]byte(mediaUser.Password), []byte(password))
	//paswords,_ := bcrypt.GenerateFromPassword([]byte(password), 10)
	//fmt.Println(string(paswords))
	if err != nil {
		appG.ResponseMsg(http.StatusOK, "密码错误", false)
		return
	}

	token, err := util.GenerateToken(mediaUser.ID)
	if err != nil {
		appG.Response(http.StatusOK, e.ERROR_AUTH_TOKEN, false)
		return
	}

	// 写入日志
	media_user_login_log_service := media_user_login_log_service.MediaUserLoginLog{
		MediaUserId: mediaUser.ID,
		//LoginIp:     c.Request.RemoteAddr, // go 如果使用自己的服务器，可以直接使用 net/http 来获取
		LoginIp:     c.GetHeader("Remote_addr"), // nginx会 转发ip到go的服务器，在通过go获取header中的remote_adder 获取用户的ip
	}

	if err := media_user_login_log_service.Add(); err != nil {
		appG.ResponseMsg(http.StatusOK, "日志写入失败", false)
		return
	}


	appG.Response(http.StatusOK, e.SUCCESS, map[string]string{
		"token": token,
	})
}
